package com.ch.clinking.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.icu.text.SimpleDateFormat;
import android.icu.util.Calendar;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentResultListener;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.ch.clinking.ClinkingApplication;
import com.ch.clinking.R;
import com.ch.clinking.Utils.NetUtils.DoCallBack;
import com.ch.clinking.Utils.NetUtils.OkHttpUtil;
import com.ch.clinking.Utils.TimeUtil;
import com.ch.clinking.activity.MainActivity;
import com.ch.clinking.adapter.Order.OrderListAdapter;
import com.ch.clinking.adapter.Order.OrderListViewAdapter;
import com.ch.clinking.adapter.Order.OrderListViewS2EAdapter;
import com.ch.clinking.bean.MerchandiseDto;
import com.ch.clinking.bean.Order;
import com.ch.clinking.bean.OrderDto;
import com.ch.clinking.bean.OrderS2EDto;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link OrderFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class OrderFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private Button orderFragmentAddButton;
    private Button buttonDatePicker, orderFragmentShareOrderButton;
    private CalendarView selectOrderCalendarView;
    private Spinner order_spinner_date_range;
    public Spinner order_changeShopSpinner;
    private Spinner orderSpinnerStateSelect;
    private ListView oderViewList;
    private TextView totalOrderOfCount;
    private ProgressBar orderFragmentLoadingProgressBar;
    private RecyclerView recyclerOderViewList;

    private String selectedDate = "";

    private SwipeRefreshLayout orderFragmentSwipeRefreshLayout;

    private ActivityResultLauncher<Intent> resultLauncher;


    private ClinkingApplication app;
    private List<OrderDto> orderList;
    private List<OrderS2EDto> orderS2EDtoList;
    private OrderListAdapter orderListAdapter;
    private OrderListViewAdapter orderListViewAdapter;
    private OrderListViewS2EAdapter orderListViewS2EAdapter;
    private OrderDto orderUpdate;

    public void setResultLauncher(ActivityResultLauncher<Intent> resultLauncher) {
        this.resultLauncher = resultLauncher;
    }


    public OrderFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment OrderFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static OrderFragment newInstance(String param1, String param2) {
        OrderFragment fragment = new OrderFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        app = ClinkingApplication.getInstance();

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onResume() {
        super.onResume();

//        refreshOrderList();
//        flashFlag = true;

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_order, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        getParentFragmentManager().setFragmentResultListener("updatedOrder", this, new FragmentResultListener() {
            @Override
            public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) {
                // 获取传递的数据
                String orderId = result.getString("updatedOrder");
                updateListWithNewData(orderId);
            }
        });


        // 切换店铺下拉框
        order_changeShopSpinner = view.findViewById(R.id.order_changeShopSpinner);
        // 快捷日期选择下拉框
        order_spinner_date_range = view.findViewById(R.id.order_spinner_date_range);
        // 订单状态下拉框
        orderSpinnerStateSelect = view.findViewById(R.id.order_spinner_state_select);
//        oderViewList = view.findViewById(R.id.oderViewList);
        totalOrderOfCount = view.findViewById(R.id.totalOrderOfCount);
        orderFragmentLoadingProgressBar = view.findViewById(R.id.orderFragmentLoadingProgressBar);
//        orderFragmentAddButton = view.findViewById(R.id.orderFragmentAddButton);
        recyclerOderViewList = view.findViewById(R.id.oderViewList);
        orderFragmentSwipeRefreshLayout = view.findViewById(R.id.orderFragmentSwipeRefreshLayout);
        buttonDatePicker = view.findViewById(R.id.button_date_picker);
        selectOrderCalendarView = view.findViewById(R.id.selectOrderCalendarView);

        orderFragmentShareOrderButton = view.findViewById(R.id.orderFragmentShareOrderButton);


        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.date_ranges, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        order_spinner_date_range.setAdapter(adapter);

        order_spinner_date_range.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    Log.d("refreshOrderList", "refreshOrderList0");
                } else {
                    String[] dateRange = getDateRange(position);
                    Log.d("refreshOrderList", "dateRange");
                    if (dateRange != null) {
                        fetchOrderInfo(dateRange[0], dateRange[1]);
                        Log.d("refreshOrderList", "fetchOrderInfo");
                    }

                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        ArrayAdapter<CharSequence> orderStateAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.order_state, android.R.layout.simple_spinner_item);
        orderStateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        orderSpinnerStateSelect.setAdapter(orderStateAdapter);
        orderSpinnerStateSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                set15DayTimeOnButton();

                if (position == 0) {
//                    buttonDatePicker.setText(showDate);
                    getAllOrderState();

                } else {
                    getOrderByState(position);
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        orderFragmentSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onRefresh() {
                refreshData();
            }
        });

        buttonDatePicker.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View v) {
                showCalendarDialog();
            }
        });


        // 初始化店铺下拉框数据
        List<String> spinnerData = new ArrayList<>();
        for (int i = 0; i < app.shopList.size(); i++) {
            spinnerData.add(app.shopList.get(i).getShopName());
        }

        // 创建适配器
        ArrayAdapter<String> shopAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, spinnerData);

        // 设置下拉框样式
        shopAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // 设置适配器
        order_changeShopSpinner.setAdapter(shopAdapter);

        // 创建页面时加载数据
//        refreshOrderList();

        // 设置下拉框点击事件
        order_changeShopSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                // 处理下拉框item点击事件
                String selectedItem = (String) parentView.getItemAtPosition(position);
                app.shopPosition = position;
                Log.d("shopPosition", String.valueOf(app.shopPosition));
                MainActivity activity = (MainActivity) requireActivity();


                if (!activity.flash) {
                    activity.refreshMerList();
                } else {
                    activity.flash = false;
                }
//                merchandiseList.clear();
//                onResume();
//                if (flashFlag) {
                refreshOrderList();
//                }
//                flashFlag = true;
//                Toast.makeText(getContext(), "Selected: " + selectedItem, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // 未选择任何item时的处理
            }
        });


        orderFragmentShareOrderButton.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View v) {
                Bitmap bitmap = getRecyclerViewScreenshot(recyclerOderViewList);
                if (bitmap != null) {
                    saveBitmapToFile(getActivity(), bitmap);
                } else {
                    Toast.makeText(getActivity(), "获取RecyclerView内容失败", Toast.LENGTH_SHORT).show();
                }
            }
        });



    }

    public void updateListWithNewData(String orderId) {

        showLoading();

        // 在这里实现更新列表数据的逻辑

        // 获取订单TAG列表
        HashMap<String, String> mer = new HashMap<>();
        mer.put("orderId", orderId);

        OkHttpUtil.getInstance().doPostForm("/order/selectOrderByOrderId", new DoCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onSuccess(String result) {
                Log.d("selectOrderByOrderId", "result:"+result);

                orderUpdate = new Gson().fromJson(result, OrderDto.class);
                orderListViewAdapter.updateOrder(orderUpdate);

                hideLoading();
            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(getActivity(), "网络错误,获取商品失败,请稍后再试", Toast.LENGTH_SHORT).show();
                hideLoading();
            }
        }, mer);

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void refreshOrderList() {

        select15DayAllStateOrder();

        // 检查当前店铺，并更新下拉框显示的店铺名称
//        order_changeShopSpinner.setSelection(app.shopPosition);

//        showLoading();
//
//        HashMap<String, String> selectMerchandiseList = new HashMap<>();
//        selectMerchandiseList.put("shopId", app.shopList.get(app.shopPosition).getShopId());
//
//        // 检查当前店铺，并更新下拉框显示的店铺名称
//        order_changeShopSpinner.setSelection(app.shopPosition);
//
//        // 设置默认所有订单提示
//        buttonDatePicker.setText("所有订单");
//
//
//        OkHttpUtil.getInstance().doPostForm("/order/selectOrderByShopId", new DoCallBack() {
//            @Override
//            public void onSuccess(String result) {
//                Log.d("selectOrderByShopId", "result:"+result);
//
//                OrderDto[] orderDtoArray = new Gson().fromJson(result, OrderDto[].class);
//                orderList = Arrays.asList(orderDtoArray);
//
//                recyclerOderViewList.setLayoutManager(new LinearLayoutManager(getContext()));
//                orderListViewAdapter = new OrderListViewAdapter(getActivity(), orderList, orderFragmentLoadingProgressBar);
//
////                orderListAdapter = new OrderListAdapter(getContext(), R.layout.list_order_layout, orderList, getParentFragmentManager());
//                recyclerOderViewList.setAdapter(orderListViewAdapter);
//                totalOrderOfCount.setText(String.valueOf(orderDtoArray.length));
//                hideLoading();
//            }
//
//            @Override
//            public void onError(Exception e) {
//                Toast.makeText(OrderFragment.this.getActivity(), "网络错误,获取商品失败,请稍后再试", Toast.LENGTH_SHORT).show();
//                hideLoading();
//            }
//        }, selectMerchandiseList);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void saveBitmapToFile(Context context, Bitmap bitmap) {
        // 获取外部存储公共目录
        File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

        // 指定 Screenshots 文件夹路径
        File screenshotsDir = new File(picturesDir, "Screenshots");

        // 确保 Screenshots 文件夹存在
        if (!screenshotsDir.exists()) {
            Toast.makeText(getActivity(), "Screenshots 文件夹不存在", Toast.LENGTH_SHORT).show();
            return;
        }



        // 创建文件对象
        File file = new File(screenshotsDir, "Order"+TimeUtil.getStringFormatTime()+".png");

        try (FileOutputStream fos = new FileOutputStream(file)) {
            // 压缩并保存位图到文件
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();

            // 通知媒体库更新
            scanMediaFile(context, file);

            Toast.makeText(getActivity(), "图片已保存到: " + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "保存图片失败", Toast.LENGTH_SHORT).show();
        }
    }

    private Bitmap getRecyclerViewScreenshot(RecyclerView recyclerView) {
        RecyclerView.Adapter adapter = recyclerView.getAdapter();
        if (adapter == null) {
            return null;
        }

        // 使用计算的总高度
        int totalHeight = getRecyclerViewTotalHeight(recyclerView);
        Bitmap bitmap = Bitmap.createBitmap(recyclerView.getWidth(), totalHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        recyclerView.draw(canvas);
        return bitmap;
    }

    private int getRecyclerViewTotalHeight(RecyclerView recyclerView) {
        int totalHeight = 0;
        RecyclerView.Adapter adapter = recyclerView.getAdapter();
        if (adapter != null) {
            for (int i = 0; i < adapter.getItemCount(); i++) {
                View itemView = recyclerView.getLayoutManager().findViewByPosition(i);
                if (itemView != null) {
                    totalHeight += itemView.getHeight();
                }
            }
        }
        return totalHeight;
    }

    // 方法用于通知相册应用更新
    private void scanMediaFile(Context context, File file) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);
    }


    private void showLoading() {
        orderFragmentLoadingProgressBar.setVisibility(View.VISIBLE);
        if (getActivity() != null) {
            getActivity().getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }
    }

    private void hideLoading() {
        orderFragmentLoadingProgressBar.setVisibility(View.GONE);
        if (getActivity() != null) {
            getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void refreshData() {
        refreshOrderList();
        // 完成刷新后停止 SwipeRefreshLayout 的刷新动画
        orderFragmentSwipeRefreshLayout.setRefreshing(false);
    }

    // 显示日历
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void showCalendarDialog() {
        final Dialog dialog = new Dialog(getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.order_calendar_dialog);

        // 设置透明背景和不允许点击对话框外部
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setCanceledOnTouchOutside(false);

        CalendarView calendarView = dialog.findViewById(R.id.orderCalendarView);
        Button btnCancel = dialog.findViewById(R.id.orderDayBtnCancel);
        Button btnConfirm = dialog.findViewById(R.id.orderDayBtnConfirm);

        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        // 设置默认选择的日期
        selectedDate = year + "-" + (month + 1) + "-" + day;

        // 设置 CalendarView 的日期为当前日期
        calendarView.setDate(calendar.getTimeInMillis(), false, true);


        calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
                selectedDate = year + "-" + (month + 1) + "-" + dayOfMonth;
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss(); // 关闭对话框
            }
        });

        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!selectedDate.equals("X")) {
                    orderSpinnerStateSelect.setSelection(0);
                    fetchOrderInfo(selectedDate);
                    buttonDatePicker.setText(selectedDate); // 更新按钮文字
                    dialog.dismiss(); // 关闭对话框
                } else {
                    Toast.makeText(getActivity(), "请选择日期", Toast.LENGTH_SHORT).show();
                }
            }
        });

        dialog.show();
    }


    private void fetchOrderInfo(String date) {

        showLoading();

        HashMap<String, String> dateTime = new HashMap<>();
        dateTime.put("shopId", app.shopList.get(app.shopPosition).getShopId());
        dateTime.put("date", date);

        OkHttpUtil.getInstance().doPostForm("/order/selectOrderOneDay", new DoCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.d("selectOrderOneDay", "result:" + result);

                order_spinner_date_range.setSelection(0);

                OrderDto[] orderDtoArray = new Gson().fromJson(result, OrderDto[].class);
                orderList = Arrays.asList(orderDtoArray);

                recyclerOderViewList.setLayoutManager(new LinearLayoutManager(getContext()));
                orderListViewAdapter = new OrderListViewAdapter(getActivity(), orderList, orderFragmentLoadingProgressBar);
                orderListViewAdapter.setResultLauncher(resultLauncher);

//                orderListAdapter = new OrderListAdapter(getContext(), R.layout.list_order_layout, orderList, getParentFragmentManager());
                recyclerOderViewList.setAdapter(orderListViewAdapter);
                totalOrderOfCount.setText(String.valueOf(orderDtoArray.length));
                hideLoading();
            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(OrderFragment.this.getActivity(), "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                hideLoading();
            }
        }, dateTime);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private String[] getDateRange(int position) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Calendar calendar = Calendar.getInstance();
        String startDate = "";
        String endDate = dateFormat.format(new Date());

        switch (position) {
            case 0:
                return null;
            case 1: // 今日
                startDate = dateFormat.format(getStartOfDay(calendar));
                break;
            case 2: // 昨天
                calendar.add(Calendar.DAY_OF_MONTH, -1);
                startDate = dateFormat.format(getStartOfDay(calendar));
                endDate = dateFormat.format(getEndOfDay(calendar));
                break;
            case 3: // 近3天
                calendar.add(Calendar.DAY_OF_MONTH, -3);
                startDate = dateFormat.format(getStartOfDay(calendar));
                break;
            case 4: // 近7天
                calendar.add(Calendar.DAY_OF_MONTH, -7);
                startDate = dateFormat.format(getStartOfDay(calendar));
                break;
            case 5: // 近7天
                calendar.add(Calendar.DAY_OF_MONTH, -15);
                startDate = dateFormat.format(getStartOfDay(calendar));
                break;
            default:
                return null;
        }

        return new String[]{startDate, endDate};
    }


    private void getAllOrderState() {

        showLoading();

        HashMap<String, String> orderStateMap = new HashMap<>();
        orderStateMap.put("shopId", app.shopList.get(app.shopPosition).getShopId());

        OkHttpUtil.getInstance().doPostForm("/order/selectAllOrder15Day", new DoCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.d("selectAllOrder15Day", "result:" + result);

                OrderDto[] orderDtoArray = new Gson().fromJson(result, OrderDto[].class);
                orderList = Arrays.asList(orderDtoArray);

                recyclerOderViewList.setLayoutManager(new LinearLayoutManager(getContext()));
                orderListViewAdapter = new OrderListViewAdapter(getActivity(), orderList, orderFragmentLoadingProgressBar);
                orderListViewAdapter.setResultLauncher(resultLauncher);

                recyclerOderViewList.setAdapter(orderListViewAdapter);
                totalOrderOfCount.setText(String.valueOf(orderDtoArray.length));
                hideLoading();
            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(OrderFragment.this.getActivity(), "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                hideLoading();
            }
        }, orderStateMap);

    }

    private void getOrderByState(int position) {

        String orderState;

        switch (position) {
            case 1: // 未下单
                orderState = "未下单";
                break;
            case 2: // 待出货
                orderState = "待出货";
                break;
            case 3: // 已出货
                orderState = "已出货";
                break;
            default:
                return;
        }

        HashMap<String, String> orderStateMap = new HashMap<>();
        orderStateMap.put("shopId", app.shopList.get(app.shopPosition).getShopId());
        orderStateMap.put("orderState", orderState);

        showLoading();

        OkHttpUtil.getInstance().doPostForm("/order/selectOrderByStage", new DoCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.d("selectOrderByStage", "result:" + result);

                OrderDto[] orderDtoArray = new Gson().fromJson(result, OrderDto[].class);
                orderList = Arrays.asList(orderDtoArray);

                recyclerOderViewList.setLayoutManager(new LinearLayoutManager(getContext()));
                orderListViewAdapter = new OrderListViewAdapter(getActivity(), orderList, orderFragmentLoadingProgressBar);

//                orderListAdapter = new OrderListAdapter(getContext(), R.layout.list_order_layout, orderList, getParentFragmentManager());
                recyclerOderViewList.setAdapter(orderListViewAdapter);
                totalOrderOfCount.setText(String.valueOf(orderDtoArray.length));
                hideLoading();
            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(OrderFragment.this.getActivity(), "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                hideLoading();
            }
        }, orderStateMap);


    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private Date getStartOfDay(Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private Date getEndOfDay(Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    private void fetchOrderInfo(String startDate, String endDate) {

        showLoading();
        Log.d("refreshOrderList", "getOrder");


        HashMap<String, String> dateTime = new HashMap<>();
        dateTime.put("shopId", app.shopList.get(app.shopPosition).getShopId());
        dateTime.put("startDate", startDate);
        dateTime.put("endDate", endDate);

        OkHttpUtil.getInstance().doPostForm("/order/selectOrderS2E", new DoCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.d("selectOrderOneDay", "result:" + result);

//                selectedDate = year + "-" + (month + 1) + "-" + day;
                String showDate = startDate.substring(5, 7) + "." + startDate.substring(8, 10) + "-" + endDate.substring(5, 7) + "." + endDate.substring(8, 10);
                Log.d("showDate", "showDate:" + showDate);
                buttonDatePicker.setText(showDate);

                OrderS2EDto[] OrderS2EDtoArray = new Gson().fromJson(result, OrderS2EDto[].class);
                orderS2EDtoList = Arrays.asList(OrderS2EDtoArray);
                Log.d("orderS2EDtoList", "orderS2EDtoList:" + orderS2EDtoList);

                recyclerOderViewList.setLayoutManager(new LinearLayoutManager(getContext()));
                orderListViewS2EAdapter = new OrderListViewS2EAdapter(getActivity(), orderS2EDtoList, orderFragmentLoadingProgressBar);

//                orderListAdapter = new OrderListAdapter(getContext(), R.layout.list_order_layout, orderList, getParentFragmentManager());
                recyclerOderViewList.setAdapter(orderListViewS2EAdapter);
                totalOrderOfCount.setText(String.valueOf(OrderS2EDtoArray.length));
                hideLoading();
            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(OrderFragment.this.getActivity(), "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                hideLoading();
            }
        }, dateTime);

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void select3DayOrder(){
        String[] dateRange = getDateRange(3);
        if (dateRange != null) {
            fetchOrderInfo(dateRange[0], dateRange[1]);
            order_spinner_date_range.setSelection(3);
        }else {
            Toast.makeText(OrderFragment.this.getActivity(), "获取3天数据出错", Toast.LENGTH_SHORT).show();
        }


    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void select15DayAllStateOrder() {
        set15DayTimeOnButton();
        getAllOrderState();
        orderSpinnerStateSelect.setSelection(0);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void set15DayTimeOnButton() {
        // 定义日期格式
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 计算15天前的时间
        LocalDateTime startOfDay = now.minusDays(15).toLocalDate().atStartOfDay();
        LocalDateTime endOfDay = now;

        // 将 LocalDateTime 格式化为字符串
        String startOfDayStr = startOfDay.format(dateTimeFormatter);
        String endOfDayStr = endOfDay.format(dateTimeFormatter);
        selectedDate = startOfDayStr.substring(5, 7) + "." + startOfDayStr.substring(8, 10) + "-" + endOfDayStr.substring(5, 7) + "." + endOfDayStr.substring(8, 10);
        buttonDatePicker.setText(selectedDate);
        order_spinner_date_range.setSelection(0);
    }


}